package com.wjm.blog.core.web;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.HierarchicalMessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.lang.Nullable;

/**
 * 抽取公共国际化资源配置, 配置默认i18n国家化资源加载
 *
 * @author jiyuan
 * @version 1.0
 * @date 2020/12/28 14:25
 */
@Configuration
@EnableAutoConfiguration
class MessageSourceConfig {

    private final static String MESSAGE_SOURCE_BEAN = "messageSource";

    @Bean
    BeanPostProcessor messageSourceExtender() {
        return new BeanPostProcessor() {
            @Override
            public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) throws BeansException {
                if (bean instanceof HierarchicalMessageSource && MESSAGE_SOURCE_BEAN.equals(beanName)) {
                    // 设置将用于尝试解析此对象无法解析的消息的父级。
                    ResourceBundleMessageSource parent = new ResourceBundleMessageSource();
                    parent.setBasename("i18n-core.message");
                    parent.setDefaultEncoding("UTF-8");
                    ((HierarchicalMessageSource) bean).setParentMessageSource(parent);
                }
                return bean;
            }
        };
    }
}